package com.guaoran.algorithm.stack;

import java.util.Stack;

/**
 * @Auth gucheng
 * @Desc 验证括号
 * @Date 2020/12/22 上午11:30
 * https://leetcode.com/problems/valid-parentheses/
 */
public class ValidParentheses {
    public static void main(String[] args) {
        String s = "()";
        System.out.println(isValid(s));//true

        s = "()[]{}";
        System.out.println(isValid(s));//true

        s = "(]";
        System.out.println(isValid(s));//false

        s = "([)]";
        System.out.println(isValid(s));//false

        s = "{[]}";
        System.out.println(isValid(s));//true

    }

    /**
     * 验证括号 ( ) { } [ ]
     * @param str
     * @return
     */
    public static boolean isValid(String str){
        if(str == null || str.length() == 0){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (char  c : str.toCharArray()) {
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            }
            if(c == ')' && (stack.isEmpty() || stack.pop() != '(')){
                return false;
            }
            if(c == '}' && (stack.isEmpty() || stack.pop() != '{')){
                return false;
            }
            if(c == ']' && (stack.isEmpty() || stack.pop() != '[')){
                return false;
            }
        }

        return stack.isEmpty();

    }
}
